package com.atguigu.tingshu.album.service.impl;

import com.atguigu.tingshu.album.config.VodProperties;
import com.atguigu.tingshu.album.service.VodService;
import com.atguigu.tingshu.common.execption.GuiguException;
import com.atguigu.tingshu.common.util.UploadFileUtil;
import com.atguigu.tingshu.vo.album.TrackMediaInfoVo;
import com.qcloud.vod.VodUploadClient;
import com.qcloud.vod.model.VodUploadRequest;
import com.qcloud.vod.model.VodUploadResponse;
import com.tencentcloudapi.common.AbstractModel;
import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.vod.v20180717.VodClient;
import com.tencentcloudapi.vod.v20180717.models.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.Map;


@Slf4j
@Service
public class VodServiceImpl implements VodService {


    @Autowired
    private VodProperties vodProperties;

    @Override
    public Map<String, Object> uploadTrack(MultipartFile file) {


        //1.构建一个vod的客户端对象
        VodUploadClient vodUploadClient = new VodUploadClient(vodProperties.getSecretId(), vodProperties.getSecretKey());

        //获取到文件在磁盘上的完整路径
        String uploadTempPath = UploadFileUtil.uploadTempPath(vodProperties.getTempPath(), file);

        //2.构建上传请求对象

        VodUploadRequest request = new VodUploadRequest();
        request.setMediaFilePath(uploadTempPath);
        request.setSubAppId(Long.parseLong(vodProperties.getAppId().toString()));
        request.setStorageRegion(vodProperties.getRegion());
        request.setConcurrentUploadNumber(5);

        //3.开始上传
        try{
            VodUploadResponse response = vodUploadClient.upload(vodProperties.getRegion(),request);
            log.info("Upload FileId = {}",response.getFileId());
            Map<String, Object> map = new HashMap<>();
            map.put("mediaFileId",response.getFileId());
            map.put("mediaUrl",response.getMediaUrl());

            return map;
        }catch(Exception e){
            //业务方法进行异常处理
            log.error("上传音频文件到vod中失败：{}",e.getMessage());
            throw new GuiguException(201,"上传音频文件到vod失败");
        }
    }

    @Override
    public TrackMediaInfoVo getMediaInfo(String mediaFileId) {
        try{
            //1.创建实例认证对象
            Credential cred = new Credential(vodProperties.getSecretId(), vodProperties.getSecretKey());

            //2.创建查询媒体信息的vod客户端对象
            VodClient client = new VodClient(cred, vodProperties.getRegion());

            //3.创建Request对象
            DescribeMediaInfosRequest req = new DescribeMediaInfosRequest();
            String[] fileIds1 = {mediaFileId};
            req.setFileIds(fileIds1);
            req.setSubAppId(Long.parseLong(String.valueOf(vodProperties.getAppId())));

            //4.发送请求 并且得到响应对象
            DescribeMediaInfosResponse resp = client.DescribeMediaInfos(req);
            System.out.println(AbstractModel.toJsonString(resp));

            MediaInfo[] mediaInfoSet = resp.getMediaInfoSet();

            if (mediaInfoSet != null && mediaInfoSet.length != 0){
                MediaInfo mediaInfo = mediaInfoSet[0];
                MediaBasicInfo basicInfo = mediaInfo.getBasicInfo();
                MediaMetaData metaData = mediaInfo.getMetaData();

                TrackMediaInfoVo trackMediaInfoVo = new TrackMediaInfoVo();
                trackMediaInfoVo.setSize(metaData.getSize());
                trackMediaInfoVo.setDuration(metaData.getDuration());
                trackMediaInfoVo.setMediaUrl(basicInfo.getMediaUrl());
                trackMediaInfoVo.setType(basicInfo.getType());
                return trackMediaInfoVo;
            }


        }catch (TencentCloudSDKException e){
            log.error("查询媒体信息失败：{}",e.getMessage());

        }
        return null;

    }

    @Override
    public void removeMediaFile(String mediaFileId) {
        try{
            // 实例化一个认证对象，入参需要传入腾讯云账户 SecretId 和 SecretKey，此处还需注意密钥对的保密
            // 代码泄露可能会导致 SecretId 和 SecretKey 泄露，并威胁账号下所有资源的安全性
            // 以下代码示例仅供参考，建议采用更安全的方式来使用密钥
            // 请参见：https://cloud.tencent.com/document/product/1278/85305
            // 密钥可前往官网控制台 https://console.cloud.tencent.com/cam/capi 进行获取
            Credential cred = new Credential(vodProperties.getSecretId(), vodProperties.getSecretKey());

            VodClient client = new VodClient(cred, vodProperties.getRegion());
            // 实例化一个请求对象,每个接口都会对应一个request对象
            DeleteMediaRequest req = new DeleteMediaRequest();
            req.setFileId(mediaFileId);
            req.setSubAppId(Long.valueOf(vodProperties.getAppId()));
            // 返回的resp是一个DeleteMediaResponse的实例，与请求对象对应
            DeleteMediaResponse resp = client.DeleteMedia(req);
            // 输出json格式的字符串回包
            System.out.println(AbstractModel.toJsonString(resp));
        } catch (TencentCloudSDKException e) {
            log.error("删除媒体信息失败：{}",e.getMessage());
            throw new GuiguException(201,"删除媒体信息失败");
        }
    }
}
